# students/crud.py

from sqlalchemy.orm import Session
from typing import List, Optional

from . import models, schemas

class CRUDStudent:
    def get_by_id(self, db: Session, student_id: str) -> Optional[models.Student]:
        return db.query(models.Student).filter(models.Student.student_id == student_id).first()

    def get_all(self, db: Session, skip: int = 0, limit: int = 100) -> List[models.Student]:
        return db.query(models.Student).offset(skip).limit(limit).all()

    def get_by_filter(self, db: Session, student_id: Optional[str] = None,
                      student_name: Optional[str] = None, class_name: Optional[str] = None) -> List[models.Student]:
        query = db.query(models.Student)
        if student_id:
            query = query.filter(models.Student.student_id == student_id)
        if student_name:
            query = query.filter(models.Student.student_name.contains(student_name))
        if class_name:
            query = query.filter(models.Student.class_name == class_name)
        return query.all()

    def create(self, db: Session, student_in: schemas.StudentCreate) -> models.Student:
        db_student = models.Student(**student_in.dict())
        db.add(db_student)
        db.commit()
        db.refresh(db_student)
        return db_student

    def update(self, db: Session, student_id: str, student_in: schemas.StudentUpdate) -> Optional[models.Student]:
        db_student = self.get_by_id(db, student_id)
        if db_student:
            update_data = student_in.dict(exclude_unset=True)
            for field, value in update_data.items():
                setattr(db_student, field, value)
            db.commit()
            db.refresh(db_student)
            return db_student

    def delete(self, db: Session, student_id: str) -> bool:
        db_student = self.get_by_id(db, student_id)
        if db_student:
            db.delete(db_student)
            db.commit()
            return True
        return False

crud_student = CRUDStudent()